<?php

class FormAction_Calendar extends FormAction
{

  public $fields = array('title' => 'event_title', 'start' => 'event_start', 'end' => 'event_end', 'allday' => 'event_allday');

  protected $action = Form::ACTION_CALENDAR;

  public function execute()
  {
    $request = s::request();

    if ($request->post('formAction') == 'calendar_get_events') {
      $this->loadData();

      $elements = $this->form->getElements($this->action);

      $data = $this->getIterator();

      $events = array();

      while ($row = $data->next()) {
        $event = array();

        $event['id'] = $row[$this->form->pk];
        $event['title'] = $row[$this->fields['title']];
        $event['start'] = strtotime($row[$this->fields['start']]);
        $event['end'] = strtotime($row[$this->fields['end']]);
        $event['allDay'] = (bool) ($row[$this->fields['allday']]);
        $event['url'] = s::response()->makeUrl($this->form->getRoute(), array(
          'action' => 'view', $this->form->pk => $row[$this->form->pk]
        ));

        $events[] = $event;
      }

      header('Content-type: application/json; charset="utf-8"');
      echo json_encode($events);
      exit();
    }

    elseif ($request->post('formAction') == 'calendar_update_event') {
      $start = intval($request->post('start'));
      $end = intval($request->post('end'));
      $allday = intval((bool) $request->post('allday'));

      $data = array();
      $data[$this->fields['start']] = date('Y-m-d H:i:s', $start);
      $data[$this->fields['end']] = $end ? date('Y-m-d H:i:s', $end) : null;
      $data[$this->fields['allday']] = $allday;

      $data = array_intersect_key($data, array_flip($this->fields));

      $data[$this->form->pk] = $request->post('id');

      $response = $this->gateway()->save($data);

      header('Content-type: application/json; charset="utf-8"');
      echo json_encode($response);
      exit();
    }
  }

  protected function loadData()
  {
    $params = array();

    $start = s::request()->post('start');
    $end = s::request()->post('end');

    $start = date('Y-m-d H:i:s', $start);
    $end = date('Y-m-d H:i:s', $end);

    $df = $this->fields['start'];

    $params['fields'] = array($this->form->pk);
    $params['fields'] = array_merge($params['fields'], array_filter($this->fields));

    $params['where'] = array("$df BETWEEN :start AND :end");
    $params['data'] = array('start' => $start, 'end' => $end);

    $params['fields'] = array_filter($params['fields']);

    $row = $this->gateway()->findAll($params);

    $this->filterDbData($row, $this->action);

    $this->formData = $row;
  }

}
